package org.jeecg.modules.zhoupackage.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.modules.degression.mapper.MlccPriceSystemPingleiMapper;
import org.jeecg.modules.degression.mapper.MyMlccPriceSystemCostRecordMapper;
import org.jeecg.modules.degression.pojo.MlccPriceSystemPinglei;
import org.jeecg.modules.gwcjava.jiekou.entity.MlccUserInfo;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.mapper.MyMlccFabricLadderPriceMapper;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.pojo.MlccFabricLadderPrice;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccCompanyInfoMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccCompanyInfo;
import org.jeecg.modules.zhoupackage.GoodsOrder.pojo.MlccThirdGoodsOrder;
import org.jeecg.modules.zhoupackage.mapper.*;
import org.jeecg.modules.zhoupackage.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 面料工具类
 *
 * @author zxl
 * @since 20200924
 */
@SuppressWarnings("all")
@Component
public class FabricUtil {

    @Autowired
    MyMlccCategoryInfoMapper mapper;

    @Autowired
    MlccFabricInfoMapper fabricInfoMapper;

    @Autowired
    CartMlccUserInfoMapper userInfoMapper;

    @Autowired
    MyMlccFabricOrderinfoMapper fabricOrderinfoMapper;

    @Autowired
    MlccGroupInfoMapper groupInfoMapper;

    @Autowired
    MyMlccSingleOrderInfoMapper singleOrderInfoMapper;

    @Autowired
    MyMlccOrderBodysizeMapper orderBodysizeMapper;

    @Autowired
    MyBodySizeMapper bodySizeMapper;

    @Autowired
    MySizeInfoMapper sizeInfoMapper;

    @Autowired
    MyContrastColorMapper contrastColorMapper;

    @Autowired
    MyMlccEmbdtypePriceMapper embdtypePriceMapper;

    @Autowired
    MyMlccModuleSmallTemplateMapper moduleSmallTemplateMapper;

    @Autowired
    MyMlccSignModuleInfoMapper signModuleInfoMapper;

    @Autowired
    MyMlccProductInfoMapper productInfoMapper;

    @Autowired
    MyEmbroColorMapper embroColorMapper;

    @Autowired
    MyProductBodySizeMapper productBodySizeMapper;

    @Autowired
    MyMlccButtonsInfoMapper buttonsInfoMapper;

    @Autowired
    MyTeamOrderMapper teamOrderMapper;

    @Autowired
    MyCustomeInfoMapper customeInfoMapper;

    @Autowired
    MyTeamMudoleMapper teamMudoleMapper;

    @Autowired
    MlccCartInfoMapper cartInfoMapper;

    @Autowired
    MyMlccPriceSystemCostRecordMapper recordMapper;

    @Autowired
    FontMapper fontMapper;

    @Autowired
    MyMlccCategoryInfoMapper categoryInfoMapper;

    @Autowired
    MyMlccFabricDiscountSystemMapper fabricDiscountSystemMapper;

    @Autowired
    MyMlccFabricDiscountGroupMapper fabricDiscountGroupMapper;

    @Autowired
    MyMlccFabricLadderDiscountMapper fabricLadderDiscountMapper;

    @Autowired
    MyMlccFabricLadderPriceMapper fabricLadderPriceMapper;

    @Autowired
    MyMlccMaterialLibuInfoMapper libuInfoMapper;

    @Autowired
    MyMlccDilinniInfoMapper dilinniInfoMapper;

    @Autowired
    MyMlccAafterSalesinfoMapper afterSalesinfoMapper;

    @Autowired
    MyTrackingOrderMapper trackingOrderMapper;

    @Autowired
    MyMlccMonthStatementsMapper monthStatementsMapper;

    @Autowired
    MyMlccCompanyInfoMapper companyInfoMapper;

    @Autowired
    MlccPriceSystemPingleiMapper priceSystemPingleiMapper;

    @Autowired
    MyMlccDiscountPricesysytemMapper discountPricesysytemMapper;

    @Autowired
    MyMlccstoreMapper storeMapper;

    /**
     * 检查库存
     *
     * @param fabricID  面料ID
     * @param buyNumber 购买数量
     * @return 面料数据
     */
    public boolean checkVoorraad(String fabricID, int buyNumber) {
        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(fabricID);
        Double inventory = fabricInfo.getInventory();
        if (inventory >= buyNumber) {
            return true;
        }
        return false;
    }

    /**
     * 检查Token是否有效
     *
     * @param token
     * @return
     */
    public boolean checkToken(String token) {
        QueryWrapper<MlccUserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("token", token);
        MlccUserInfo userInfo = userInfoMapper.selectOne(wrapper);
        return userInfo != null ? true : false;
    }


    /**
     * 获取面料折扣（新版）
     *
     * @param userid  客户ID
     * @param groupid 面料组ID
     */
    public double userFabricDiscount(String userid, String groupid) {
        double result = 1L;
        // 查询用户的折扣类型
        MlccUserInfo userInfo = userInfoMapper.selectById(userid);
        // 获取公司的折扣
        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> cwrapper = new QueryWrapper<>();
        cwrapper.eq("company_code", userInfo.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(cwrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            userInfo = companyUser;
        }

        if (userid != null) {
            // 客户折扣类型表ID
            String discountid = userInfo.getDiscount();
            QueryWrapper<MlccFabricDiscountGroup> wrapper = new QueryWrapper<>();
            wrapper.eq("fabric_discount_system_id", discountid).eq("fabric_gourp_id", groupid);
            MlccFabricDiscountGroup discountGroup = fabricDiscountGroupMapper.selectOne(wrapper);
            if (discountGroup != null) {
                result = Double.valueOf(discountGroup.getDiscountRatio());
                System.out.println("拿到的面料折扣是多少？" + result);
            }
        }
        return result;
    }

    /**
     * 根据token获取用户ID
     *
     * @param token
     * @return
     */
    public int getUserIDByToken(String token) {
        QueryWrapper<MlccUserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("token", token);
        return userInfoMapper.selectOne(wrapper).getId();
    }

    /**
     * 根据token获取当前空户详情
     *
     * @param token
     * @return
     */
    public MlccUserInfo getUserDetail(String token) {
        QueryWrapper<MlccUserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("token", token);
        return userInfoMapper.selectOne(wrapper);
    }

    /**
     * 获取面料订单列表
     *
     * @param page    分页器
     * @param token   令牌
     * @param time    查询时间
     * @param endtime 结束时间
     * @param status  状态
     * @param code    订单编码
     * @return
     */
    public IPage<MyOrderEntity> getFabricOrderList(Page<MyOrderEntity> page, String token, String time, String endtime,
                                                   Integer status, String code, String fabricCode, String emp, String cusname) {
        if (!checkToken(token)) return null;
        MlccUserInfo detail = getUserDetail(token);
        int userid = getUserIDByToken(token);
        QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userid).in("status", -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
        List<MlccFabricOrderinfo> orderinfos = fabricOrderinfoMapper.selectList(wrapper);
        HashSet<String> cartid = new HashSet<>();
        for (MlccFabricOrderinfo orderinfo : orderinfos) {
            cartid.add(orderinfo.getCartId());
        }
        // 注意：这里才是查询真正的订单列表
        System.out.println("当前账号code+++++++++++++" + detail.getOrgCode());
        IPage<MyOrderEntity> result = fabricOrderinfoMapper.getFabricOrder(page, token, cartid, time, endtime, status, code, detail.getOrgCode(), fabricCode, emp, cusname);
        return result;
    }

    /**
     * 前端获取现货订单列表
     *
     * @param page    分页器
     * @param userId  下单账号
     * @param token   令牌
     * @param time    开始时间
     * @param endtime 结束时间
     * @param status  状态
     * @param code    编号
     */
    public IPage<MlccThirdGoodsOrder> getGoodsOrderList(Page<MlccThirdGoodsOrder> page, Integer userId, String token, String time, String endtime, Integer status, String code) {
        if (!checkToken(token)) return null;
        MlccUserInfo detail = getUserDetail(token);
        int userid = getUserIDByToken(token);
        IPage<MlccThirdGoodsOrder> goodsOder = fabricOrderinfoMapper.getGoodsOder(page, time, endtime, status, code, detail.getOrgCode());
        // 查询下单门店和下单员工
        List<MlccThirdGoodsOrder> records = goodsOder.getRecords();
        if (records != null && records.size() > 0) {
            for (MlccThirdGoodsOrder record : records) {
                // 查询下单门店
                MlccStoreInfo storeInfo = storeMapper.selectById(record.getStoreId());
                record.setEmpName(detail.getRealname());
                if (storeInfo != null) {
                    record.setStoreName(storeInfo.getStoreName());
                }
            }
        }
        return goodsOder;
    }


    /**
     * 我的订单界面获取个订列表
     *
     * @param page   分页器
     * @param token  令牌
     * @param time   查询时间
     * @param status 状态
     * @param code   订单编码
     */
    public IPage<MlccSingleOrderInfo> getSingleOrderList(Page<MlccSingleOrderInfo> page, Integer userId, String token, String time, String endtime,
                                                         Integer status, String code, String cusname, String emp) {
        if (!checkToken(token)) return null;
        MlccUserInfo detail = getUserDetail(token);
        return fabricOrderinfoMapper.getSingleOder(page, time, endtime, status, code, detail.getOrgCode(), cusname, emp);
    }

    /**
     * 我的订单界面获取团订列表
     *
     * @param page   分页器
     * @param token  令牌
     * @param time   查询时间
     * @param status 状态
     * @param code   订单编码
     */
    public IPage<MlccTeamOrderInfo> getTeamOrderList(Page<MlccTeamOrderInfo> page, Integer userId, String token, String time, String endtime,
                                                     Integer status, String code, String companyName, String emp) {
        if (!checkToken(token)) return null;
        MlccUserInfo detail = getUserDetail(token);

        IPage<MlccTeamOrderInfo> iPage = fabricOrderinfoMapper.getTeamOder(page, time, endtime, status, code, detail.getOrgCode(), companyName, emp);
        List<MlccTeamOrderInfo> records = iPage.getRecords();
        for (MlccTeamOrderInfo record : records) {
            if (record.getCustomerId() != null && !"".equals(record.getCustomerId())) {
                MlccCustomerInfo customerInfo = customeInfoMapper.selectById(record.getCustomerId());
                if (customerInfo != null)
                    record.setCustomerName(customerInfo.getCustomerName()).setCustomerCode(customerInfo.getCustomerCode());
            }
        }
        return iPage;
    }

    /**
     * 给查询到的购物车列表里面的面料添加价格
     *
     * @param farbicOrderList
     * @return
     */
    public List<CartEntity> addPrice(List<CartEntity> farbicOrderList) {
        // 遍历购物车
        for (CartEntity entity : farbicOrderList) {
            // 获取面料基本信息
            MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(entity.getFabricId());
            addPrice(fabricInfo, entity.getBuyNumber());
            entity.setFabricPrice(fabricInfo.getFabricPrice());
        }
        return farbicOrderList;
    }

    /**
     * 给查询到的面料列表添加价格(Set方式)
     *
     * @param hashset
     */
    public HashSet<MlccFabricInfo> addPrice(HashSet<MlccFabricInfo> hashset) {
        if (hashset.size() == 0) return null;
        for (MlccFabricInfo fabricInfo : hashset) {
            /*如果面料表的组ID为空，说明有自己的单价，直接计算*/
            if (fabricInfo.getGroupId() != null) {
                MlccGroupInfo groupInfo = groupInfoMapper.selectById(fabricInfo.getGroupId());
                if (groupInfo != null) {
                    fabricInfo.setFabricPrice(groupInfo.getPrice());
                } else {
                    fabricInfo.setFabricPrice(BigDecimal.ONE);
                }

            }
        }
        return hashset;
    }

    /**
     * 给查询到的面料列表添加价格(List方式)
     *
     * @param hashset
     * @return
     */
    public ArrayList<MlccFabricInfo> addPrice(ArrayList<MlccFabricInfo> hashset) {
        for (MlccFabricInfo fabricInfo : hashset) {
            /*如果面料表的组ID为空，说明有自己的单价，直接计算*/
            if (fabricInfo.getGroupId() != null) {
                MlccGroupInfo groupInfo = groupInfoMapper.selectById(fabricInfo.getGroupId());
                fabricInfo.setFabricPrice(groupInfo.getPrice());
            }
        }
        return hashset;
    }

    /**
     * 给查询到的面料列表添加价格(单个面料)
     *
     * @param info   面料对象
     * @param buynum 购买数量
     */
    public MlccFabricInfo addPrice(MlccFabricInfo info, Double buynum) {
        /*如果面料表的组ID为空，说明有自己的单价，直接计算*/
        if (info != null) {
//            info.getGroupId() != null
            if (info.getFabricPrice().compareTo(new BigDecimal(0)) == 0) {
                MlccGroupInfo groupInfo = groupInfoMapper.selectById(info.getGroupId());
                if (groupInfo != null) {
                    // 给面料找到区间售价
                    List<MlccFabricLadderPrice> ladderPrices = groupPrice(info.getGroupId());
                    if (ladderPrices != null && ladderPrices.size() > 0) {
                        for (MlccFabricLadderPrice ladderPrice : ladderPrices) {
                            // 如果有符合的区间，就把区间的价格给面料
                            if (buynum >= ladderPrice.getMinNumbers() && buynum < ladderPrice.getMaxNumbers()) {
                                info.setFabricPrice(ladderPrice.getPrice());
                                break;
                            } else {
                                // 如果没有符合的区间，就使用面料组的默认售价
                                info.setFabricPrice(groupInfo.getPrice());
                            }
                        }
                    } else {
                        // 如果没有符合的区间，就使用面料组的默认售价
                        info.setFabricPrice(groupInfo.getPrice());
                    }
                }
            }
            return info;
        }
        return null;
    }

    /**
     * 获取面料组的区间售价 （调用此方法需要判断面料不是主推面料）
     *
     * @param groupid 面料组ID
     */
    public List<MlccFabricLadderPrice> groupPrice(String groupid) {
        QueryWrapper<MlccFabricLadderPrice> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id", groupid);
        return fabricLadderPriceMapper.selectList(wrapper);
    }

    /**
     * 给面料添加折扣
     *
     * @param set
     * @return
     */
    public HashSet<MlccFabricInfo> addJietizhekou(HashSet<MlccFabricInfo> set) {
        for (MlccFabricInfo entity : set) {
            /*如果面料有组尝试获取则扣*/
            if (entity.getGroupId() != null) {
                MlccGroupInfo groupInfo = groupInfoMapper.selectById(entity.getGroupId());
                /*判断是否有折扣*/
                if (groupInfo.getDiscount() != null) {
                    entity.setJietiZk(Double.valueOf(groupInfo.getDiscount()));
                }
            } else {
                entity.setJietiZk(1.0);
            }
        }
        return set;
    }

    /**
     * 添加客户折扣(个订的方式)
     *
     * @param orderID
     * @param set
     * @return
     */
    @Deprecated
    public HashSet<MlccFabricInfo> addkhzk(String orderSn, HashSet<MlccFabricInfo> set) {
        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSingleOrderInfo orderInfo = singleOrderInfoMapper.selectOne(wrapper);
        MlccUserInfo mlccUserInfo = userInfoMapper.selectById(orderInfo.getUserId());
        // 查询discount
        String discount = cartInfoMapper.getDiscount(mlccUserInfo.getDiscount(), 1);
        if (discount != null && !"".equals(discount)) {
            for (MlccFabricInfo entity : set) {
                entity.setKehuzk(Double.valueOf(discount));
            }
        } else {
            for (MlccFabricInfo entity : set) {
                entity.setKehuzk(1);
            }
        }
        return set;
    }

    /**
     * 添加客户折扣(团订的方式)
     *
     * @param orderID
     * @param set
     * @return
     */
    public HashSet<MlccFabricInfo> addkhzktd(String orderSn, HashSet<MlccFabricInfo> set) {
        if (set == null || set.size() == 0) return null;
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo orderInfo = teamOrderMapper.selectOne(wrapper);
        MlccUserInfo mlccUserInfo = userInfoMapper.selectById(orderInfo.getUserId());
        // 查询discount
        String discount = cartInfoMapper.getDiscount(mlccUserInfo.getDiscount(), 2);
        if (discount != null && !"".equals(discount)) {
            for (MlccFabricInfo entity : set) {
                entity.setKehuzk(Double.valueOf(discount));
            }
        } else {
            for (MlccFabricInfo entity : set) {
                entity.setKehuzk(1);
            }
        }
        return set;
    }

    /**
     * 添加客户折扣(团订模板的方式)
     *
     * @param orderID
     * @param set
     * @return
     */
    public HashSet<MlccFabricInfo> addkhzktdModule(String orderSn, HashSet<MlccFabricInfo> set) {
        QueryWrapper<MlccTeamModuleInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamModuleInfo orderInfo = teamMudoleMapper.selectOne(wrapper);
        MlccUserInfo mlccUserInfo = userInfoMapper.selectById(orderInfo.getUserId());
        // 查询discount
        String discount = cartInfoMapper.getDiscount(mlccUserInfo.getDiscount(), 2);
        if (discount != null && !"".equals(discount)) {
            for (MlccFabricInfo entity : set) {
                entity.setKehuzk(Double.valueOf(discount));
            }
        } else {
            for (MlccFabricInfo entity : set) {
                entity.setKehuzk(1);
            }
        }
        return set;
    }

    /**
     * 个订模板添加客户折扣
     *
     * @param orderID
     * @param set
     * @return
     */
    public HashSet<MlccFabricInfo> moudleaddkhzk(String orderSn, HashSet<MlccFabricInfo> set) {
        QueryWrapper<MlccSignModuleInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSignModuleInfo orderInfo = signModuleInfoMapper.selectOne(wrapper);
        MlccUserInfo mlccUserInfo = userInfoMapper.selectById(orderInfo.getUserId());
        // 查询discount
        String discount = cartInfoMapper.getDiscount(mlccUserInfo.getDiscount(), 1);
        if (discount != null && !"".equals(discount)) {
            for (MlccFabricInfo entity : set) {
                entity.setKehuzk(Double.valueOf(discount));
            }
        } else {
            for (MlccFabricInfo entity : set) {
                entity.setKehuzk(1);
            }
        }
        return set;
    }

    /**
     * 根据订单号获取客户折扣(个订方式)
     *
     * @param orderSn   订单编号
     * @param productid 产品id
     */
    public Double getkhzk(String orderSn, String productid) {
        System.out.println("**************以下是获取个订的工艺折扣*****************");
        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSingleOrderInfo orderInfo = singleOrderInfoMapper.selectOne(wrapper);
        // 获取下单账号
        MlccUserInfo mlccUserInfo = userInfoMapper.selectById(orderInfo.getUserId());
        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> cwrapper = new QueryWrapper<>();
        cwrapper.eq("company_code", mlccUserInfo.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(cwrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            mlccUserInfo = companyUser;
        }


        // 查询工艺的折扣
        // 获取产品信息
        MlccProductInfo productInfo = productInfoMapper.selectById(productid);
        // 获取产品的工艺类型ID
        String gylx = getGYLXFromProduct(productInfo);
        String plid = getpingleiFromProduct(productInfo);
        System.out.println("品类id>>>>>>>>>>>>" + plid);
        System.out.println("工艺ID》》》》》》》》" + gylx);
        // 这是原来的工艺类型对象，没有设置折扣
        MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(gylx);
        if (categoryInfo != null) {
            /*注意：需要重新定位到真正的工艺id，此时查到的是前端展示，与设置折扣的工艺不是同一个，但是编号相同*/
            QueryWrapper<MlccCategoryInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("category_code", categoryInfo.getCategoryCode()).eq("topid", plid)
                    .eq("is_type", 4).eq("status", 0);
            // 这是查询到了设置了折扣的工艺
            MlccCategoryInfo newCategoryInfo = categoryInfoMapper.selectOne(wrapper1);
            if (newCategoryInfo != null) {
                categoryInfo = newCategoryInfo;
            }
        }

        if (categoryInfo != null) {
            // 确定价格体系
            QueryWrapper<MlccPriceSystemPinglei> wrapper3 = new QueryWrapper<>();
            wrapper3.eq("category_id", categoryInfo.getId()).eq("business_type", 0).eq("is_gongyi", 1);
            MlccPriceSystemPinglei systemPinglei = priceSystemPingleiMapper.selectOne(wrapper3);
            if (systemPinglei != null) {
                // 确定工艺折扣
                QueryWrapper<MlccDiscountPricesystem> pricesysytemQueryWrapper = new QueryWrapper<>();
                pricesysytemQueryWrapper.eq("discount_type_id", mlccUserInfo.getDiscount())
                        .eq("price_system_id", systemPinglei.getId());
                MlccDiscountPricesystem mlccDiscountPricesysytem = discountPricesysytemMapper.selectOne(pricesysytemQueryWrapper);
                if (mlccDiscountPricesysytem != null) {
                    System.out.println("折扣数据》》》》》》》》》》》》" + mlccDiscountPricesysytem);
                    return Double.valueOf(mlccDiscountPricesysytem.getDiscountRatio());
                }
            }
        }

        return new Double(1);
    }

    /**
     * 根据订单号获取客户折扣(团订订单方式)
     *
     * @param orderSn
     * @return
     */
    public Double getkhzktd(String orderSn) {
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo orderInfo = teamOrderMapper.selectOne(wrapper);
        MlccUserInfo mlccUserInfo = userInfoMapper.selectById(orderInfo.getUserId());

        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> cwrapper = new QueryWrapper<>();
        cwrapper.eq("company_code", mlccUserInfo.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(cwrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            mlccUserInfo = companyUser;
        }

        // 查询discount
        String discount = cartInfoMapper.getDiscount(mlccUserInfo.getDiscount(), 2);
        if (discount != null && !"".equals(discount)) {
            return Double.valueOf(discount);
        } else {
            return 1.0;
        }
    }

    /**
     * 根据订单号获取客户折扣(团订模板方式)
     *
     * @param orderSn
     * @return
     */
    public Double getkhzktdModule(String orderSn) {
        QueryWrapper<MlccTeamModuleInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamModuleInfo orderInfo = teamMudoleMapper.selectOne(wrapper);
        MlccUserInfo mlccUserInfo = userInfoMapper.selectById(orderInfo.getUserId());

        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> cwrapper = new QueryWrapper<>();
        cwrapper.eq("company_code", mlccUserInfo.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(cwrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            mlccUserInfo = companyUser;
        }

        // 查询discount
        String discount = cartInfoMapper.getDiscount(mlccUserInfo.getDiscount(), 2);
        if (discount != null && !"".equals(discount)) {
            return Double.valueOf(discount);
        } else {
            return 1.0;
        }
    }

    /**
     * 根据模板号获取客户折扣(个订模板)
     *
     * @param orderSn
     * @return
     */
    public Double moudlegetkhzk(String orderSn) {
        QueryWrapper<MlccSignModuleInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSignModuleInfo orderInfo = signModuleInfoMapper.selectOne(wrapper);
        MlccUserInfo mlccUserInfo = userInfoMapper.selectById(orderInfo.getUserId());

        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> cwrapper = new QueryWrapper<>();
        cwrapper.eq("company_code", mlccUserInfo.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(cwrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            mlccUserInfo = companyUser;
        }

        // 查询discount
        String discount = cartInfoMapper.getDiscount(mlccUserInfo.getDiscount(), 1);
        if (discount != null && !"".equals(discount)) {
            return Double.valueOf(discount);
        } else {
            return 1.0;
        }
    }

    /**
     * 给类别数据添加价格并计算价格
     *
     * @param list
     * @return
     *//*
    public List<MlccCategoryInfo> addCategoryPrice(String order_sn, List<MlccCategoryInfo> list) {
        for (MlccCategoryInfo categoryInfo : list) {
            QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", order_sn);
            MlccSingleOrderInfo orderInfo = singleOrderInfoMapper.selectOne(wrapper);
            MlccUserInfo mlccUserInfo = userInfoMapper.selectById(orderInfo.getUserId());
            categoryInfo.setKehuzk(Double.valueOf(mlccUserInfo.getDiscount()));
            *//*计算折后单价*//*
            double afterPrice = categoryInfo.getCost().doubleValue() * Double.valueOf(categoryInfo.getDiscount()) * categoryInfo.getKehuzk();
            categoryInfo.setAfterPrice(afterPrice);
            *//*计算折扣总价*//*
            categoryInfo.setAfterAll(afterPrice);
        }
        return list;
    }

    *//**
     * 计算订单总价格
     *
     * @param fabricList
     * @param categoryList
     * @return
     *//*
    public String getOrderMoney(HashSet<MlccFabricInfo> fabricList, List<MlccCategoryInfo> categoryList) {
        double money = 0;
        for (MlccFabricInfo fabricInfo : fabricList) {
            money += fabricInfo.getAllPrice();
        }
        for (MlccCategoryInfo categoryInfo : categoryList) {
            money += categoryInfo.getAfterAll();
        }
        return money + "";
    }

    *//**
     * 根据绣字ID获取绣字价格
     *
     * @param xiuziID
     * @return
     *//*
    public double getXiuziPrice(int xiuziID) {
        return embdtypePriceMapper.selectById(xiuziID).getRetailPrice().doubleValue();
    }*/


    /******************************************************这是个订详情的最新版**********************************************************************************
     * 获取个订订单详情（根据产品的版本,全部数据跟着产品走）
     *
     * @param orderSn 订单编号
     */
    public MlccSingleOrderInfo getSingleOrderDetailById3(String orderSn) {
        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectOne(wrapper);
        ArrayList<MlccFabricInfo> allFabric = new ArrayList<>(); // 用来存放这个订单中的所有面料

        // 查询下单门店
        QueryWrapper<MlccStoreInfo> storeInfoQueryWrapper = new QueryWrapper<>();
        storeInfoQueryWrapper.eq("store_code", singleOrderInfo.getStoreId());
        MlccStoreInfo storeInfo = storeMapper.selectOne(storeInfoQueryWrapper);
        if (storeInfo != null) {
            singleOrderInfo.setStoreName(storeInfo.getStoreName());
        }

        // 查询下单电源
        if (singleOrderInfo != null && singleOrderInfo.getUserId() != null && !"".equals(singleOrderInfo.getUserId())) {
            MlccUserInfo mlccUserInfo = userInfoMapper.selectById(singleOrderInfo.getUserId());
            if (mlccUserInfo != null) {
                singleOrderInfo.setEmpName(mlccUserInfo.getRealname()).setEmpPhone(mlccUserInfo.getPhone());
            }
        }

        // 查询支付时间
        QueryWrapper<MlccTrackingOrder> wrapper9 = new QueryWrapper<>();
        wrapper9.eq("order_sn", orderSn).eq("order_status", 1);
        MlccTrackingOrder trackingOrder = trackingOrderMapper.selectOne(wrapper9);
        if (trackingOrder != null) {
            singleOrderInfo.setPayTime(trackingOrder.getCreateTime());
        }

        /*如果没有产品关联，直接返回*/
        if (singleOrderInfo == null || singleOrderInfo.getChanpingIds() == null) {
            return singleOrderInfo;
        }
        // 用户基本信息
        MlccUserInfo userDetail = userInfoMapper.selectById(singleOrderInfo.getUserId());
        // 创建一个变量，用来计算订单价格（计算价格的时机：制造个订下单界面点击提交订单的时候进行计算）
        BigDecimal orderMoney = new BigDecimal(0);
        // 1、获取订单中的产品数据
        List<String> chanpingids = Arrays.asList(singleOrderInfo.getChanpingIds().split(","));
        QueryWrapper<MlccProductInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.in("id", chanpingids).orderByDesc("create_time");
        List<MlccProductInfo> productInfoList = productInfoMapper.selectList(wrapper1);// 这是所有的产品
        singleOrderInfo.setProductInfoList(productInfoList);

        /*这里开始，在产品列表中进行查询数据*/
        for (MlccProductInfo newProductInfo : productInfoList) {
            // 1、查询产品的数量
            if (newProductInfo.getCategoryIds() != null) {
                // 查询产品的品类名称
                String pingleiid = getpingleiFromProduct(newProductInfo);
                MlccCategoryInfo pingleiDetail = categoryInfoMapper.selectById(pingleiid);
                if (pingleiDetail != null) {
                    // 查询到了品类的名称
                    newProductInfo.setPingleiName(pingleiDetail.getCategoryName());
                }

                // 查询产品的工艺类型
                String gylx = getGYLX(newProductInfo);
                System.out.println("工艺类型ID:" + gylx);
                MlccCategoryInfo gylxentity = categoryInfoMapper.selectById(gylx);
                System.out.println(gylxentity);
                if (gylxentity != null) {
                    // 查询到了产品的工艺类型
                    newProductInfo.setGyname(gylxentity.getCategoryName());
                }

                List<String> CategoryIdSet = Arrays.asList(newProductInfo.getCategoryIds().split(","));// 每个产品中的类别ID
                /*2、品类版型的查询（产品数据中categoryid对应数据的isType为1的数据）*/
                QueryWrapper<MlccCategoryInfo> wrapper2 = new QueryWrapper<>();
                wrapper2.in("id", CategoryIdSet).in("is_type", 1, 2, 3, 4);
                List<MlccCategoryInfo> plbxs = mapper.selectList(wrapper2);
                // 给每一个品类查询他的上级名称，就是模块下的小模块表的名称
                for (MlccCategoryInfo plbx : plbxs) {

                    plbx.setSmallTemplateName(moduleSmallTemplateMapper.selectById(plbx.getParentId()).getParameter());
                }
                newProductInfo.setPlbx(plbxs);
            }

            // 20201201 查询绣字颜色信息和字体信息
            // 先查询绣字的颜色数据
            if (newProductInfo != null && newProductInfo.getXiuziColor() != null) {
                newProductInfo.setXiuziColorEntity(embroColorMapper.selectById(newProductInfo.getXiuziColor()));
            }

            // 查询绣字的高度信息
            if (newProductInfo != null && newProductInfo.getXiuziHeight() != null && !"".equals(newProductInfo.getXiuziHeight())) {
                System.out.println("高度=====" + newProductInfo.getXiuziHeight());
                newProductInfo.setHeight(embdtypePriceMapper.selectById(newProductInfo.getXiuziHeight()).getEmbroideredHeight());
            }

            // 查询字体的一些信息
            if (newProductInfo != null && newProductInfo.getXiuziZiti() != null && !"".equals(newProductInfo.getXiuziZiti())) {
                newProductInfo.setFont(fontMapper.selectById(newProductInfo.getXiuziZiti()));
            }

            // 3、从产品数据中查询面料数据
            if (newProductInfo.getFabricIds() != null && !"".equals(newProductInfo.getFabricIds())) {
                double zhekou = 1;
                // 存放这个产品的下的所有面料
                HashSet<MlccFabricInfo> fabricInfoSet = new HashSet<>();
                // 查询产品的面料ids 面料id/购买米数
                List<String> fabricids = Arrays.asList(newProductInfo.getFabricIds().split(","));
                if (fabricids != null && fabricids.size() > 0) {
                    // 循环遍历
                    for (String fabricid : fabricids) {
                        String[] split = fabricid.split("/");
                        // 查询到面料的基本信息
                        MlccFabricInfo mlccFabricInfos = fabricInfoMapper.selectById(split[0]);
                        if (mlccFabricInfos != null) {
                            newProductInfo.setFabricCode(mlccFabricInfos.getFabricCode());
                            mlccFabricInfos.setMishu(split[1]);
                            // 重新查询面料的价格(拿到了标准单价)
                            mlccFabricInfos = addPrice(mlccFabricInfos, Double.valueOf(split[1]));
                            if (mlccFabricInfos != null && mlccFabricInfos.getGroupId() != null) {
                                // 获取面料折扣
                                zhekou = userFabricDiscount(userDetail.getId() + "", mlccFabricInfos.getGroupId());
                                mlccFabricInfos.setKehuzk(zhekou);
                                fabricInfoSet.add(mlccFabricInfos);
                            } else {
                                mlccFabricInfos.setKehuzk(1);
                            }
                            mlccFabricInfos.setFabricRemark(newProductInfo.getFabricRemark());
                            allFabric.add(mlccFabricInfos);
                        }
                    }
                }
            }

            /*查询里布数据*/
            if (newProductInfo.getLibuId() != null && !"".equals(newProductInfo.getLibuId())) {
                MlccMaterialLibuInfo libuInfo = libuInfoMapper.selectById(newProductInfo.getLibuId());
                newProductInfo.setLibuInfo(libuInfo);
            }

            /*查询低领尼数据*/
            if (newProductInfo.getDilinliId() != null && !"".equals(newProductInfo.getDilinliId())) {
                MlccDilinniInfo dilinniInfo = dilinniInfoMapper.selectById(newProductInfo.getDilinliId());
                newProductInfo.setDilinniInfo(dilinniInfo);
            }

            /*下一步。。。*/
            if (newProductInfo.getCategoryIds() != null) {
                List<String> CategoryIdSet = Arrays.asList(newProductInfo.getCategoryIds().split(","));// 每个产品中的类别ID
                // 4、查询款式与工艺（根据categoryid来查询，但是is_type必须为0）
                QueryWrapper<MlccCategoryInfo> wrapper4 = new QueryWrapper<>();
                wrapper4.in("id", CategoryIdSet).eq("is_type", 0);
                List<MlccCategoryInfo> ksgys = mapper.selectList(wrapper4);
                // 给每一个品类查询他的上级名称，就是模块下的小模块表的名称
                for (MlccCategoryInfo ksgy : ksgys) {
                    MlccModuleSmallTemplate template = cartInfoMapper.getSmall(ksgy.getParentId());
//                    MlccModuleSmallTemplate template = moduleSmallTemplateMapper.selectById(ksgy.getParentId());
                    if (template != null) {
                        ksgy.setSmallTemplateName(template.getParameter());
                    }
                }
                newProductInfo.setKsgy(ksgys);
            }
            /*下一步*/
            // 6、撞色数据
            if (newProductInfo.getZhuangseIds() != null && !"".equals(newProductInfo.getZhuangseIds())) {
                HashSet<String> hzuangseidSet = new HashSet<>();// 遍历获取撞色ID
                String[] hzuangseidArray = newProductInfo.getZhuangseIds().split(",");// 格式：撞色ID/颜色名称
                for (String zhuangseid : hzuangseidArray) {
                    hzuangseidSet.add(zhuangseid); // 原来的方式
                }
                if (hzuangseidSet.size() > 0) {
                    List<MlccContrastcolorInfo> infoArrayList = new ArrayList<>(); // 用来存储单个产品下的所有撞色
                    for (String idAndColorName : hzuangseidSet) {
                        String[] split = idAndColorName.split("/");
                        QueryWrapper<MlccContrastcolorInfo> wrapper3 = new QueryWrapper<>();
                        wrapper3.in("id", split[0]);
                        // 现在拿到了所有的撞色数据，但是还没有具体的颜色
                        MlccContrastcolorInfo contrastcolorInfo = contrastColorMapper.selectById(split[0]);
                        if (split.length > 1) {
                            contrastcolorInfo.setColorName(split[1]);
                        }
                        infoArrayList.add(contrastcolorInfo);
                    }
                    newProductInfo.setAllConColor(infoArrayList);
                }
            }
            /*下一步*/
            // 7、获取产品中的尺寸信息(身体数据，注意与体型表区别)
            if (newProductInfo.getBodySizeIds() != null) {
                HashSet<MlccProductBodysize> bodySizeSet = new HashSet<>();
                // 用产品ID可以到达产品尺寸关联表
                QueryWrapper<MlccProductBodysize> wrapper5 = new QueryWrapper<>();
                wrapper5.eq("product_id", newProductInfo.getId()).eq("isfanxiu", 0);
                List<MlccProductBodysize> productBodysizes = productBodySizeMapper.selectList(wrapper5);
                for (MlccProductBodysize bodysize : productBodysizes) {
                    // 根据查询到的尺寸，区分是净体尺寸还是成衣尺寸
                    MlccBodySizeInfo bodySizeInfo = bodySizeMapper.selectById(bodysize.getBodysizeId());
                    if (bodySizeInfo != null) {
                        bodysize.setIsJin(bodySizeInfo.getIsJin());
                    }
                    bodySizeSet.add(bodysize);
                }
                for (MlccProductBodysize probodysize : bodySizeSet) {
                    String categoryId = bodySizeMapper.selectById(probodysize.getBodysizeId()).getCategoryId();
                    probodysize.setTypeName(mapper.selectById(categoryId).getCategoryName());
                    probodysize.setSizeName(bodySizeMapper.selectById(probodysize.getBodysizeId()).getBodySizename());
                    probodysize.setUnit(bodySizeMapper.selectById(probodysize.getBodysizeId()).getUnit());
                }
                /*ArrayList<MlccProductBodysize> list = new ArrayList<>(bodySizeSet);*/
                /*for (int i = 0; i < list.size() - 1; i++) {
                    for (int j = 1; j < list.size(); j++) {
                        if (list.get(i).getBodysizeId().equals(list.get(j).getBodysizeId()) && list.get(i).getBodysizeValue().equals(list.get(j).getBodysizeValue())) {
                            list.remove(i);
                        }
                    }
                }*/
                /*HashSet<MlccProductBodysize> set = new HashSet<>(list);*/
                // 成衣尺寸与净体尺寸分开
                Map<Integer, List<MlccProductBodysize>> collect = bodySizeSet.stream().collect(Collectors.groupingBy(MlccProductBodysize::getIsJin));
                // 0是成衣尺寸
                List<MlccProductBodysize> cheng = collect.get(0);
                // 1是净体尺寸
                List<MlccProductBodysize> jing = collect.get(1);
                newProductInfo.setProductBodySizeList(bodySizeSet);
                newProductInfo.setCheng(cheng);
                newProductInfo.setJing(jing);
            }
            /*下一步*/
            // 8、加工费用（也就是产品费用）
            if (newProductInfo.getZhehouPrice() != null) {
                double orderPrice = 0;
                // 获取客户折扣
                Double kehuzhekou = getkhzk(orderSn, newProductInfo.getId());
                newProductInfo.setKhzk(kehuzhekou);
                newProductInfo.setAfterzhekouPrice(newProductInfo.getZheqianPrice().multiply(new BigDecimal(kehuzhekou)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                newProductInfo.setAllPrice(newProductInfo.getZheqianPrice().multiply(new BigDecimal(kehuzhekou)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                orderPrice += newProductInfo.getAllPrice();
                orderMoney = orderMoney.add(new BigDecimal(newProductInfo.getAllPrice()));
            }
            /*下一步*/
            // 9、查询纽扣列表
            if (newProductInfo.getButtonsIds() != null) {
                List<String> buttonIDList = Arrays.asList(newProductInfo.getButtonsIds().split(","));
                QueryWrapper<MlccButtonsInfo> buttonwrapper = new QueryWrapper<>();
                buttonwrapper.in("id", buttonIDList);
                newProductInfo.setButtonsInfoList(buttonsInfoMapper.selectList(buttonwrapper));
            }
            /*下一步*/
            // 10、查询体型数据
            if (newProductInfo.getSizeIds() != null) {
                List<String> sizeIds = Arrays.asList(newProductInfo.getSizeIds().split(","));
                QueryWrapper<MlccSizeInfo> sizeInfoQueryWrapper = new QueryWrapper<>();
                sizeInfoQueryWrapper.in("id", sizeIds);
                List<MlccSizeInfo> mlccSizeInfoList = sizeInfoMapper.selectList(sizeInfoQueryWrapper);// 这个时候还需要拿到父级的名称
                for (MlccSizeInfo mlccSizeInfo : mlccSizeInfoList) {
                    if (mlccSizeInfo != null && !"0".equals(mlccSizeInfo.getParentId())) {
                        mlccSizeInfo.setSizeName(sizeInfoMapper.selectById(mlccSizeInfo.getParentId()).getSizeName());
                    }
                }
                newProductInfo.setSizeInfoList(mlccSizeInfoList);
            }
            /*下一步*/
            // 11 计算订单金额
            /*if (newProductInfo.getZheqianPrice() != null) {
                Double khzk = getkhzk(orderSn,);
                // 计算出产品的折后价格
                BigDecimal proPrice = newProductInfo.getZheqianPrice().multiply(new BigDecimal(khzk));
                orderMoney = orderMoney.add(proPrice);
            }*/
        }

        // 计算面料价格
        for (MlccFabricInfo fabricInfo : allFabric) {
            if (fabricInfo != null) {
                if (fabricInfo.getFabricPrice() == null) {
                    fabricInfo.setFabricPrice(new BigDecimal(0));
                }
                // 计算折后单价
                BigDecimal multiply = fabricInfo.getFabricPrice().multiply(new BigDecimal(fabricInfo.getKehuzk()));
                fabricInfo.setAfterPrice(multiply.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                // 计算单重面料的总价
                BigDecimal multiply1 = new BigDecimal(fabricInfo.getAfterPrice()).multiply(new BigDecimal(Double.valueOf(fabricInfo.getMishu())));
                fabricInfo.setAllPrice(multiply1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                orderMoney = orderMoney.add(new BigDecimal(fabricInfo.getAllPrice()));
            }
        }

        // 更新订单的价格的时机：这条订单是草稿订单(个订下单界面最后一步需要查看订单详情，订单金额)
        if (singleOrderInfo.getStatus().equals(0)) {
            singleOrderInfo.setOrderMoney(orderMoney.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "");
            singleOrderInfoMapper.updateById(singleOrderInfo);
        }
        singleOrderInfo.setAllFabric(allFabric);
        return singleOrderInfo;
    }

    /******************************************************这是个订详情的最新版**********************************************************************************
     * 获取个订模板详情（根据产品的版本,全部数据跟着产品走）
     *
     * @param orderSn 订单编号
     * @return
     */
    public MlccSignModuleInfo getSingleMoudleDetailById3(String orderSn) {
        QueryWrapper<MlccSignModuleInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSignModuleInfo singleOrderInfo = signModuleInfoMapper.selectOne(wrapper);

        /*如果没有产品关联，直接返回*/
        if (singleOrderInfo == null || singleOrderInfo.getChanpinIds() == null) {
            return singleOrderInfo;
        }

        /*谁用拼音谁是狗*/
        if (singleOrderInfo.getMianliaoSource() != null)
            singleOrderInfo.setFabricSource(singleOrderInfo.getMianliaoSource());
        if (singleOrderInfo.getYewuType() != null)
            singleOrderInfo.setBusinessSource(singleOrderInfo.getYewuType());
        if (singleOrderInfo.getKuaidiId() != null)
            singleOrderInfo.setCourierId(singleOrderInfo.getKuaidiId());
        if (singleOrderInfo.getKuhuCode() != null)
            singleOrderInfo.setCustomerCode(singleOrderInfo.getKuhuCode());
        if (singleOrderInfo.getKuhuName() != null)
            singleOrderInfo.setCustomerName(singleOrderInfo.getKuhuName());
        if (singleOrderInfo.getChanpinIds() != null)
            singleOrderInfo.setChanpingIds(singleOrderInfo.getChanpinIds());
        if (singleOrderInfo.getTemplateName() != null)
            singleOrderInfo.setOrderName(singleOrderInfo.getTemplateName());
        if (singleOrderInfo.getKuhuSex() != null)
            singleOrderInfo.setCustomerSex(singleOrderInfo.getKuhuSex());
        if (singleOrderInfo.getOrderSn() != null)
            // 注意：这里把模板编号给了templateSn，之后Order用来存放订单编号
            singleOrderInfo.setTemplateSn(singleOrderInfo.getOrderSn());

        // 1、获取订单中的产品数据
        List<String> chanpingids = Arrays.asList(singleOrderInfo.getChanpinIds().split(","));
        QueryWrapper<MlccProductInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.in("id", chanpingids);
        List<MlccProductInfo> productInfoList = productInfoMapper.selectList(wrapper1);// 这是所有的产品
        singleOrderInfo.setProductInfoList(productInfoList);

        int flag = 0;
        /*这里开始，在产品列表中进行查询数据*/
        for (MlccProductInfo newProductInfo : productInfoList) {

            // 这里把产品里的订单编号拿出来，给外层的orderSn
            if (newProductInfo.getOrderSn() != null && flag == 0) {
                singleOrderInfo.setOrderSn(newProductInfo.getOrderSn());
                flag += 1;
            }

            if (newProductInfo.getCategoryIds() != null) {
                List<String> CategoryIdSet = Arrays.asList(newProductInfo.getCategoryIds().split(","));// 每个产品中的类别ID
                /*2、品类版型的查询（产品数据中categoryid对应数据的isType为1的数据）*/
                QueryWrapper<MlccCategoryInfo> wrapper2 = new QueryWrapper<>();
                wrapper2.in("id", CategoryIdSet).in("is_type", 1, 2, 3, 4);
                List<MlccCategoryInfo> plbxs = mapper.selectList(wrapper2);
                // 给每一个品类查询他的上级名称，就是模块下的小模块表的名称
                for (MlccCategoryInfo plbx : plbxs) {
                    plbx.setSmallTemplateName(moduleSmallTemplateMapper.selectById(plbx.getParentId()).getParameter());
                }
                newProductInfo.setPlbx(plbxs);
            }

            // 3、从产品数据中查询面料与辅料数据
            if (newProductInfo.getFabricIds() != null) {
                HashSet<MlccFabricInfo> fabricInfoSet = new HashSet<>();
                List<String> fabricids = Arrays.asList(newProductInfo.getFabricIds().split(","));// 面料id/米数这种格式
                for (String fabricid : fabricids) {
                    String[] split = fabricid.split("/");
                    MlccFabricInfo mlccFabricInfos = fabricInfoMapper.selectById(split[0]);
                    if (mlccFabricInfos != null) {
                        mlccFabricInfos.setMishu(split[1]);
                        fabricInfoSet.add(mlccFabricInfos);
                    }
                }
                // 查询面料的价格
                HashSet<MlccFabricInfo> fabricprice = addPrice(fabricInfoSet);
                fabricprice = moudleaddkhzk(orderSn, fabricprice);
                ArrayList<MlccFabricInfo> fabricInfos = new ArrayList<>(fabricprice);
                newProductInfo.setFabricList(fabricInfos);
            }
            /*下一步。。。*/
            if (newProductInfo.getCategoryIds() != null) {
                List<String> CategoryIdSet = Arrays.asList(newProductInfo.getCategoryIds().split(","));// 每个产品中的类别ID
                // 4、查询款式与工艺（根据categoryid来查询，但是is_type必须为0）
                QueryWrapper<MlccCategoryInfo> wrapper4 = new QueryWrapper<>();
                wrapper4.in("id", CategoryIdSet).eq("is_type", 0);
                List<MlccCategoryInfo> ksgys = mapper.selectList(wrapper4);
                // 给每一个品类查询他的上级名称，就是模块下的小模块表的名称
                for (MlccCategoryInfo ksgy : ksgys) {
                    MlccModuleSmallTemplate template = cartInfoMapper.getSmall(ksgy.getParentId());
//                    MlccModuleSmallTemplate template = moduleSmallTemplateMapper.selectById(ksgy.getParentId());
                    if (template != null) {
                        ksgy.setSmallTemplateName(template.getParameter());
                    }
                }
                newProductInfo.setKsgy(ksgys);
            }
            /*下一步*/
            // 6、撞色数据
            if (newProductInfo.getZhuangseIds() != null && !"".equals(newProductInfo.getZhuangseIds())) {
                HashSet<String> hzuangseidSet = new HashSet<>();// 遍历获取撞色ID
                String[] hzuangseidArray = newProductInfo.getZhuangseIds().split(",");// 格式：撞色ID/颜色名称
                for (String zhuangseid : hzuangseidArray) {
                    hzuangseidSet.add(zhuangseid); // 原来的方式
                }
                if (hzuangseidSet.size() > 0) {
                    List<MlccContrastcolorInfo> infoArrayList = new ArrayList<>(); // 用来存储单个产品下的所有撞色
                    for (String idAndColorName : hzuangseidSet) {
                        String[] split = idAndColorName.split("/");
                        QueryWrapper<MlccContrastcolorInfo> wrapper3 = new QueryWrapper<>();
                        wrapper3.in("id", split[0]);
                        // 现在拿到了所有的撞色数据，但是还没有具体的颜色
                        MlccContrastcolorInfo contrastcolorInfo = contrastColorMapper.selectById(split[0]);
                        if (split.length > 1) {
                            contrastcolorInfo.setColorName(split[1]);
                        }
                        infoArrayList.add(contrastcolorInfo);
                    }
                    newProductInfo.setAllConColor(infoArrayList);
                }
            }

            // 老的版本
                /*{
                HashSet<String> hzuangseidSet = new HashSet<>();// 遍历获取撞色ID
                String[] hzuangseidArray = newProductInfo.getZhuangseIds().split(",");
                for (String zhuangseid : hzuangseidArray) {
                    hzuangseidSet.add(zhuangseid);
                }
                if (hzuangseidSet.size() > 0) {
                    QueryWrapper<MlccContrastcolorInfo> wrapper3 = new QueryWrapper<>();
                    wrapper3.in("id", hzuangseidSet);
                    // 现在拿到了所有的撞色数据，但是还没有具体的颜色
                    List<MlccContrastcolorInfo> contrastcolorInfos = contrastColorMapper.selectList(wrapper3);
                    for (MlccContrastcolorInfo everyConColoer : contrastcolorInfos) {
                        if (everyConColoer.getEmColorId() != null && !"".equals(everyConColoer.getEmColorId())) {
                            everyConColoer.setColorName(embroColorMapper.selectById(everyConColoer.getEmColorId()).getColorName());
                        }
                    }
                    newProductInfo.setAllConColor(contrastcolorInfos);
                }
            }*/
            /*下一步*/
            // 7、获取产品中的尺寸信息(身体数据，注意与体型表区别)
            if (newProductInfo.getBodySizeIds() != null) {
                HashSet<MlccProductBodysize> bodySizeSet = new HashSet<>();
                // 用产品ID可以到达产品尺寸关联表
                QueryWrapper<MlccProductBodysize> wrapper5 = new QueryWrapper<>();
                wrapper5.eq("product_id", newProductInfo.getId());
                List<MlccProductBodysize> productBodysizes = productBodySizeMapper.selectList(wrapper5);
                for (MlccProductBodysize bodysize : productBodysizes) {
                    bodySizeSet.add(bodysize);
                }
                for (MlccProductBodysize probodysize : bodySizeSet) {
                    String categoryId = bodySizeMapper.selectById(probodysize.getBodysizeId()).getCategoryId();
                    probodysize.setTypeName(mapper.selectById(categoryId).getCategoryName());
                    probodysize.setSizeName(bodySizeMapper.selectById(probodysize.getBodysizeId()).getBodySizename());
                }
                newProductInfo.setProductBodySizeList(bodySizeSet);
            }
            /*下一步*/
            // 8、加工费用（也就是产品费用）
            if (newProductInfo.getZheqianPrice() != null) {
                BigDecimal orderPrice = new BigDecimal(0);
                Double kehuzhekou = moudlegetkhzk(orderSn);// 客户折扣
                newProductInfo.setKhzk(kehuzhekou);
                BigDecimal zhekoup = newProductInfo.getZheqianPrice().multiply(new BigDecimal(kehuzhekou));
                newProductInfo.setAfterzhekouPrice(zhekoup.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                BigDecimal allp = newProductInfo.getZheqianPrice().multiply(new BigDecimal(kehuzhekou));
                newProductInfo.setAllPrice(allp.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                orderPrice = orderPrice.add(new BigDecimal(newProductInfo.getAllPrice())).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            /*下一步*/
            // 9、查询纽扣列表
            if (newProductInfo.getButtonsIds() != null) {
                List<String> buttonIDList = Arrays.asList(newProductInfo.getButtonsIds().split(","));
                QueryWrapper<MlccButtonsInfo> buttonwrapper = new QueryWrapper<>();
                buttonwrapper.in("id", buttonIDList);
                newProductInfo.setButtonsInfoList(buttonsInfoMapper.selectList(buttonwrapper));
            }
            /*下一步*/
            // 10、查询体型数据
            if (newProductInfo.getSizeIds() != null) {
                List<String> sizeIds = Arrays.asList(newProductInfo.getSizeIds().split(","));
                QueryWrapper<MlccSizeInfo> sizeInfoQueryWrapper = new QueryWrapper<>();
                sizeInfoQueryWrapper.in("id", sizeIds);
                List<MlccSizeInfo> mlccSizeInfoList = sizeInfoMapper.selectList(sizeInfoQueryWrapper);// 这个时候还需要拿到父级的名称
                for (MlccSizeInfo mlccSizeInfo : mlccSizeInfoList) {
                    if (mlccSizeInfo != null && !"0".equals(mlccSizeInfo.getParentId())) {
                        mlccSizeInfo.setSizeName(sizeInfoMapper.selectById(mlccSizeInfo.getParentId()).getSizeName());
                    }
                }
                newProductInfo.setSizeInfoList(mlccSizeInfoList);
            }
        }
        return singleOrderInfo;
    }

    /**
     * 获取产品的品类ID
     *
     * @param product 产品对象
     */
    public String getpingleiFromProduct(MlccProductInfo product) {
        String categoryid = null;
        if (product != null && product.getCategoryIds() != null) {
            String[] split = product.getCategoryIds().split(",");
            if (split != null && split.length > 0) {
                for (String id : split) {
                    MlccCategoryInfo info = categoryInfoMapper.selectById(id);
                    if (info != null) {
                        if (info.getIsType() == 2) {
                            categoryid = id;
                        }
                    }
                }
            }
        }
        return categoryid;
    }

    /**
     * 根据品类id获取品类名称
     *
     * @param product 产品对象
     */
    public String getplNameFromProduct(MlccProductInfo product) {
        String id = getpingleiFromProduct(product);
        MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(id);
        if (categoryInfo != null) {
            return categoryInfo.getCategoryName();
        } else {
            return "";
        }
    }

    /**
     * 获取产品的工艺
     *
     * @param product 产品对象
     */
    public String getGYLXFromProduct(MlccProductInfo product) {
        String categoryid = null;
        if (product != null && product.getCategoryIds() != null) {
            String[] split = product.getCategoryIds().split(",");
            if (split != null && split.length > 0) {
                for (String id : split) {
                    MlccCategoryInfo info = categoryInfoMapper.selectById(id);
                    if (info != null) {
                        if (info.getIsType() == 4) {
                            categoryid = id;
                        }
                    }
                }
            }
        }
        return categoryid;
    }

    /**
     * 获取产品的版号
     *
     * @param product 产品对象
     */
    public String getBHFromProduct(MlccProductInfo product) {
        String categoryid = null;
        if (product != null && product.getCategoryIds() != null) {
            String[] split = product.getCategoryIds().split(",");
            if (split != null && split.length > 0) {
                for (String id : split) {
                    MlccCategoryInfo info = categoryInfoMapper.selectById(id);
                    if (info != null) {
                        if (info.getIsType() == 3) {
                            categoryid = id;
                        }
                    }
                }
            }
        }
        return categoryid;
    }

    /**
     * 获取产品的定制项参数集合
     *
     * @param product 产品对象
     */
    public List<String> getDDZXFromProduct(MlccProductInfo product) {
        ArrayList<String> result = new ArrayList<>();
        if (product != null && product.getCategoryIds() != null) {
            String[] split = product.getCategoryIds().split(",");
            if (split != null && split.length > 0) {
                for (String id : split) {
                    MlccCategoryInfo info = categoryInfoMapper.selectById(id);
                    if (info != null && info.getIsType() == 0) {
                        result.add(id);
                    }
                }
            }
        }
        return result;
    }

    /**
     * 根据定制项id获取定制项编号
     *
     * @param dzxid 定制项集合
     */
    public List<String> dzxCode(List<String> dzxid) {
        List<String> list = new ArrayList<>();
        for (String id : dzxid) {
            MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(id);
            if (categoryInfo != null) {
                list.add(categoryInfo.getCategoryCode());
            }
        }
        return list;
    }

    /**
     * 售后订单的支付
     *
     * @param price      售后价格
     * @param token      令牌
     * @param afterOrder 售后订单对象
     */
    public int payAfterOrder(BigDecimal price, String token, MlccAfterSalesinfo afterOrder) {
        // 首先进行支付
        if (!checkToken(token)) return 0; // 校验token
        MlccUserInfo userDetail = getUserDetail(token);
        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> cwrapper = new QueryWrapper<>();
        cwrapper.eq("company_code", userDetail.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(cwrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            userDetail = companyUser;
        }


        BigDecimal userbalance = new BigDecimal(Double.valueOf(userDetail.getAccountBalance())); // 用户余额金额
        // 判断用户的总余额是否充足？ 0足够，1余额不足
        int check = cheakMoney(userDetail, price);
        if (check == 1) {
            return -2;
        }
        /*进行支付
         查询抵扣额度，是否需要从抵扣额度进行扣款？
         如果抵扣额度足够支付订单金额*/
        if (userDetail.getDeductionLimit().doubleValue() >= price.doubleValue()) {
            // 更新抵扣额度
            userDetail.setDeductionLimit(userDetail.getDeductionLimit().subtract(price).setScale(2, BigDecimal.ROUND_HALF_UP));
            // 面料订单只有抵扣额度支付
            afterOrder.setDeductionPay(price);
        } else {
            // 抵扣额度不够支付订单，加上月结剩余额度是否足够支付？
            // 如果抵扣额度加上月结剩余额度足够支付订单，进行支付
            if (userDetail.getDeductionLimit().add(userDetail.getRemainingLimit()).doubleValue() >= price.doubleValue()) {
                BigDecimal subtract = new BigDecimal(price.doubleValue());
                // 抵扣额度是否是负数？？？
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    // 扣除抵扣额度的价格
                    subtract = price.subtract(userDetail.getDeductionLimit());
                }

                // 更新订单基本信息
                afterOrder.setMonthPay(subtract);
                // 更新账号的抵扣额度和月结剩余额度，抵扣额度清零
                userDetail.setRemainingLimit(userDetail.getRemainingLimit().subtract(subtract).setScale(2, BigDecimal.ROUND_HALF_UP));
                // 大于0才清空，否则不清空
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    afterOrder.setDeductionPay(userDetail.getDeductionLimit());
                    userDetail.setDeductionLimit(new BigDecimal(0));
                }
            } else {
                // 三个额度加起来菜足够支付
                // 订单剩下的钱
                BigDecimal subtract = new BigDecimal(price.doubleValue());
                // 如果抵扣额度不是负数
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    // 扣除抵扣额度的价格
                    subtract = price.subtract(userDetail.getDeductionLimit());
                }
                // 如果月结额度不是负数
                if (userDetail.getRemainingLimit().doubleValue() > 0) {
                    // 扣除月结额度的价格
                    subtract = price.subtract(userDetail.getRemainingLimit());
                }

                // 更新订单基本信息
                afterOrder.setBalancePay(subtract);
                // 更新账号的抵扣额度和月结剩余额度和账户余额，抵扣额度清零，月结额度清零！！
                userDetail.setAccountBalance(userbalance.subtract(subtract).setScale(2, BigDecimal.ROUND_FLOOR).toString());

                // 大于0才清空，否则不清空
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    afterOrder.setDeductionPay(userDetail.getDeductionLimit());
                    userDetail.setDeductionLimit(new BigDecimal(0));
                }
                if (userDetail.getRemainingLimit().doubleValue() > 0) {
                    afterOrder.setMonthPay(userDetail.getRemainingLimit());
                    userDetail.setRemainingLimit(new BigDecimal(0));
                }
            }
        }
        // 更新售后订单表的金额
        afterSalesinfoMapper.updateById(afterOrder);

        // 向月结流水表添加数据
        if (afterOrder.getMonthPay() != null) {
            savepay(userDetail.getId() + "", afterOrder.getMonthPay(), afterOrder.getOrderSn(), afterOrder.getOrdertype(), 1);
        }
        // 更新用户的余额或月结额度
        return userInfoMapper.updateById(userDetail);
    }


    /**
     * 根据产品获取产品的工艺类型
     *
     * @param productInfo 产品对象
     */
    public String getGYLX(MlccProductInfo productInfo) {
        String categoryid = null;
        String[] split = productInfo.getCategoryIds().split(",");
        if (split != null && split.length > 0) {
            for (String id : split) {
                MlccCategoryInfo info = categoryInfoMapper.selectById(id);
                if (info.getIsType() == 4) {
                    categoryid = id;
                }
            }
        }
        return categoryid;
    }

    /**
     * 根据订单编号获取用户基本信息
     *
     * @param orderSn   订单编号
     * @param orderType 订单类型
     */
    public MlccUserInfo getuserByOrder(String orderSn, Integer orderType) {
        MlccUserInfo user = null;
        if (orderType == 0) {
            // 个订订单
            QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccSingleOrderInfo orderInfo = singleOrderInfoMapper.selectOne(wrapper);
            if (orderInfo != null) {
                user = userInfoMapper.selectById(orderInfo.getUserId());
            }
        } else if (orderType == 1) {
            // 团订订单
            QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccTeamOrderInfo orderInfo = teamOrderMapper.selectOne(wrapper);
            if (orderInfo != null) {
                user = userInfoMapper.selectById(orderInfo.getUserId());
            }
        }
        return user;
    }

    /**
     * 检查金额是否足够支付订单
     *
     * @param userInfo   用户信息
     * @param orderMoney 订单金额
     * @return 0余额足够；1余额不足
     */
    public int cheakMoney(MlccUserInfo userInfo, BigDecimal orderMoney) {
        // 转化余额
        BigDecimal yue = new BigDecimal(Double.valueOf(userInfo.getAccountBalance()));
        // 这个用户一共有多少钱？
        BigDecimal allMoney = userInfo.getDeductionLimit().add(userInfo.getRemainingLimit()).add(yue);
        // 如果余额足够支付
        if (allMoney.doubleValue() >= orderMoney.doubleValue()) {
            return 0;
        } else {
            // 余额不足
            return 1;
        }
    }

    /**
     * 订单支付支付
     *
     * @param userid    支付人id
     * @param money     月结支付的金额
     * @param orderSn   订单编号
     * @param orderType 订单类型：0面料订单，1个订订单，2团订订单，3成衣订单
     * @param isAfter   0正常订单 1售后
     */
    public void savepay(String userid, BigDecimal money, String orderSn, Integer orderType, Integer isAfter) {
        MlccMonthStatements statements = new MlccMonthStatements();
        statements.setUserId(userid).setMoney(money).setOrderSn(orderSn).setOrderType(orderType).setIsAfter(isAfter);
        monthStatementsMapper.insert(statements);
    }
}
